package com.example.jobseek;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import domain.PersonaVO;
import android.support.v7.app.ActionBarActivity;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Paint;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Perfil extends ActionBarActivity {

	Bundle bundle;
	String datosLog;
	String personaJson;
	TextView nombre;
	TextView ciudad;
	TextView curriculum;
	JSONArray datos;
    JSONObject persona;
    JsonObject jobj;
    String archivo;
    String nombre_archivo;

    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_perfil);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		
		bundle = this.getIntent().getExtras();
        datosLog = bundle.getString("rut");
        
        nombre = (TextView)findViewById(R.id.txtNombre);
        ciudad = (TextView)findViewById(R.id.txtCiudad);
        curriculum = (TextView)findViewById(R.id.txtDocumento);
        
        jobj = new Gson().fromJson(datosLog, JsonObject.class);
        
        
		try {
			personaJson = new listPersona().execute(jobj.get("run").toString().replace("\"", "")).get();
			archivo = new archivo().execute(jobj.get("run").toString().replace("\"", "")).get();
			datos = new JSONArray(personaJson);
			persona = datos.getJSONObject(0);
			nombre.setText(persona.getString("nombre")+" "+persona.getString("apellido"));
			ciudad.setText(persona.getString("ciudad"));
			nombre_archivo = "CV_"+persona.getString("nombre")+"_"+persona.getString("apellido")+".docx";
			
			if (archivo.equals("No archivo")){
				curriculum.setVisibility(View.GONE);
				
			}else{	
				curriculum.setText(nombre_archivo);
				makeTextViewHyperlink(curriculum);
				//curriculum.setPaintFlags(curriculum.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);
			}
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		        
	}
	
	public void onClick(View v){
		
		
		final File root = new File(Environment.getExternalStorageDirectory()+"/");
		final File f = new File(Environment.getExternalStorageDirectory()+"/Download");
		final File directory = new File(Environment.getExternalStorageDirectory()+"/temp/");
		directory.mkdirs();
		final File dwldsPath = new File(Environment.getExternalStorageDirectory(),"/temp/"+nombre_archivo);
		
        byte[] pdfAsBytes = Base64.decode(archivo, Base64.DEFAULT);
        
        FileOutputStream os;
        try {
        	
			os = new FileOutputStream(dwldsPath, false);
			os.write(pdfAsBytes);
			os.flush();
			os.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d("download", "File.toByteArray() error");
			e.printStackTrace();
		}
        
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = "application/msword";
        intent.setDataAndType(Uri.fromFile(dwldsPath), type);
        startActivity(intent);  
        try {
			delete(dwldsPath);
			delete(directory);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        MediaScannerConnection.scanFile(this, new String[] { root.getAbsolutePath() }, null, null);
		MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath() }, null, null);
		MediaScannerConnection.scanFile(this, new String[] { dwldsPath.getAbsolutePath() }, null, null);
		MediaScannerConnection.scanFile(this, new String[] { directory.getAbsolutePath() }, null, null);

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.perfil, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {

		case R.id.home:
			System.out.println("apretado");
			break;
			
		case R.id.attach:
			Intent intent = new Intent(Perfil.this, Explore.class);
			Bundle bundle = new Bundle();
			bundle.putString("rut", datosLog);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.edit:
			Intent i = new Intent(Perfil.this, EditarPerfil.class);
			Bundle b = new Bundle();
			b.putString("datos", personaJson);
			b.putString("rut", datosLog);
			i.putExtras(b);
			startActivity(i);
			break;
		case R.id.logout:
			Intent i3 = new Intent(Perfil.this, Principal.class);
			startActivity(i3);
			break;

		}
		return true;
	}
	
	class listPersona extends AsyncTask<String, Void, String> {
		private static final String TAG = "getDatosPersona";
		ProgressDialog progressDialog;

		

		@Override
		protected String doInBackground(String... params) {
			String run = params[0];

			String result = "";

			try {

				PersonaVO personaVO = new PersonaVO(run);
				result = obtenerDatosPersona(personaVO);

				Log.i(TAG, result);

			} catch (Exception e) {
				Log.e(TAG, e.getCause().toString());
			}

			return result;
		}

		
 }
	
	class archivo extends AsyncTask<String, Void, String> {
		private static final String TAG = "archivoget";
		@Override
		protected String doInBackground(String... params) {
			String run = params[0];

			String result = "";

			try {

				PersonaVO personaVO = new PersonaVO(run);
				result = obtenerArchivo(personaVO);

				Log.i(TAG, result);

			} catch (Exception e) {
				Log.e(TAG, e.getCause().toString());
			}

			return result;
		}

		
 }
	
	
	
	public String obtenerDatosPersona(PersonaVO oPersonaVO) {
		String result ="";
		String method = "getDatosPersona";
		String TAG = method;
		Log.i("intentando enviar datos al ws usando: ", method);

		try {
			String SOAP_ACTION = util.Constantes.NAMESPACE + "#" + method;

			SoapObject request = new SoapObject(util.Constantes.NAMESPACE,
					method);

			Gson gson = new Gson();
			String persona = gson.toJson(oPersonaVO);

			request.addProperty("json", persona);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER12);

			envelope.setOutputSoapObject(request);

			envelope.addMapping(util.Constantes.NAMESPACE, "PersonaVO",
					new PersonaVO().getClass());

			HttpTransportSE transporte = new HttpTransportSE(
					util.Constantes.URL);
			transporte.debug = true;

			transporte.call(SOAP_ACTION, envelope);

			Log.i(TAG, "dump Request: " + transporte.requestDump);
			Log.i(TAG, "dump Response: " + transporte.responseDump);

			Vector response = (Vector) envelope.getResponse();
			result = (String)response.get(1);
			return result;

		} catch (Exception e) {
			e.printStackTrace();

		}

		return null;

	}
	
	
	
	public String obtenerArchivo(PersonaVO oPersonaVO) {
		String result ="";
		String method = "getArchivo";
		String TAG = method;
		Log.i("intentando enviar datos al ws usando: ", method);

		try {
			String SOAP_ACTION = util.Constantes.NAMESPACE + "#" + method;

			SoapObject request = new SoapObject(util.Constantes.NAMESPACE,
					method);

			Gson gson = new Gson();
			//String persona = gson.toJson(oPersonaVO);

			request.addProperty("rut", oPersonaVO.getRut());

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER12);

			envelope.setOutputSoapObject(request);

			envelope.addMapping(util.Constantes.NAMESPACE, "PersonaVO",
					new PersonaVO().getClass());

			HttpTransportSE transporte = new HttpTransportSE(
					util.Constantes.URL);
			transporte.debug = true;

			transporte.call(SOAP_ACTION, envelope);

			Log.i(TAG, "dump Request: " + transporte.requestDump);
			Log.i(TAG, "dump Response: " + transporte.responseDump);

			Vector response =  (Vector) envelope.getResponse();
			result = (String)response.get(1);
			return result;

		} catch (Exception e) {
			e.printStackTrace();

		}

		return null;

	}
	
	void delete(File f) throws IOException {
		
	    if (f.isDirectory()) {
	    	
	        for (File c : f.listFiles()) {
	        	System.out.println("Eliminando"+c.getAbsolutePath());
	            delete(c);
	        }
	    }
	  
 }
	
	public void makeTextViewHyperlink(TextView tv) {
		  SpannableStringBuilder ssb = new SpannableStringBuilder();
		  ssb.append(tv.getText());
		  ssb.setSpan(new URLSpan("#"), 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		  tv.setText(ssb, TextView.BufferType.SPANNABLE);
		} 
	
	 
}

